package org.restorator.dao.tx;

import org.apache.commons.dbcp.BasicDataSource;
import org.restorator.exception.DataStoreException;
import org.restorator.utill.GeneralUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.*;
import java.sql.SQLException;
import java.util.Properties;

/**
 *
 * @author Snisar Bogdan.
 */
public class DbcpDataSourceProvider implements DataSourceFactory {
//    /home/bozon/IdeaProjects/Work/src/main/resources/rdbc.properties

    private static Logger logger = LoggerFactory.getLogger(GeneralUtil.getClassName());


    private Properties properties;
    private BasicDataSource dataSource;

    public DbcpDataSourceProvider() throws IOException {
       properties  = new Properties();
       InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(PROP_FILE_NAME);
       properties.load(inputStream);
       init();

    }

    private void init() {
        dataSource = new BasicDataSource();
        dataSource.setUsername(properties.getProperty("jdbc.user"));
        dataSource.setPassword(properties.getProperty("jdbc.password"));
        dataSource.setUrl(properties.getProperty("jdbc.url"));
        dataSource.setDriverClassName(properties.getProperty("jdbc.driver"));
//        dataSource.setDefaultTransactionIsolation();

        logger.trace("Transaction manager set up. {}", properties);
    }

    @Override
    public DataSource getDataSource() throws DataStoreException {
        if(dataSource != null) {
            return dataSource;
        } else {
            throw new DataStoreException();
        }
    }

    @Override
    public Properties getDataSourceProperties() {
        return properties;
    }


    @Override
    public void close() throws SQLException {
        if(dataSource!= null) dataSource.close();
    }
}
